package com.bx.implatform.portal.utils;

import org.apache.tomcat.util.codec.binary.Base64;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

public class SignatureUtils {

    /**
     * 生成签名（规则：字典序排序参数 + MD5）
     *
     * @param params    请求参数（不含签名）
     * @param secretKey 密钥
     */
    public static String generateSign(Map<String, String> params, String secretKey, String key43) throws Exception {
        // 1. 按字典序排序参数名
        List<String> sortedKeys = params.keySet()
                .stream()
                .sorted(SignatureUtils::compareLexicographically)
                .toList();
        // 2. 拼接键值对：key1=value1&key2=value2
        StringBuilder sb = new StringBuilder();
        for (String key : sortedKeys) {
            String value = params.get(key);

            // 判断是否为JSON对象/数组（简单但有效的检测）
            boolean isJson = (value.startsWith("{") && value.endsWith("}")) ||
                    (value.startsWith("[") && value.endsWith("]"));

            sb.append(key)
                    .append("=")
                    // .append(isJson ? value : URLEncoder.encode(value, StandardCharsets.UTF_8))
                    .append(params.get(key))
                    .append("&");
        }
        // 3. 末尾追加密钥
        sb.append("appSecret=").append(secretKey);
        System.out.println("加密前签名 = " + sb);
        // 4. MD5 加密
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest = md.digest(sb.toString().getBytes());
        System.out.println("加密后签名 = " + Base64.encodeBase64String(digest));
        return Base64.encodeBase64String(digest);
    }

    /**
     * 字典序比较规则（区分大小写、数字优先）
     */
    private static int compareLexicographically(String a, String b) {
        return a.compareTo(b); // 直接使用 String 的字典序比较
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        String param = "appKey=szjkIUrAVKH7IuIdkSg5&description=这是一次创建待办的测试&detailUrlVo={\"pcUrl\":\"\",\"appUrl\":\"\"}&dueTime=null&executorIds=[\"1933361998939148290\"]&operatorId=1933361999450853377&priority=20&sourceId=46&subject=测试待办标题&timestamp=1750300207&todoType=TODO&appSecret=VYhLd_4Vhq4NPuJ3PVLmPzc2l5ZKH9k9lG6phwt8A8x4k_ET9Ddsiz0fBfRQmPPO";
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest = md.digest(param.getBytes());
        System.out.println("加密后签名 = " + Base64.encodeBase64String(digest));
    }
}